package com.sykj.bsc.rwl.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sykj.bsc.rwl.po.SysDept;
import com.sykj.bsc.rwl.po.SysRole;
import com.sykj.bsc.rwl.po.SysUser;
import com.sykj.bsc.rwl.po.extend.SysMenuExtend;
import com.sykj.bsc.rwl.po.extend.SysUserExtend;
import com.sykj.bsc.rwl.service.SysDeptService;
import com.sykj.bsc.rwl.service.SysUserService;
import com.sykj.bsc.rwl.util.JsonUtils;

@Controller
@RequestMapping("user")
public class SysUserController {
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysDeptService sysDeptService;
	
	@RequestMapping("index")
	public String index(Model model,HttpServletRequest req) throws Exception {
		String account=(String) SecurityUtils.getSubject().getPrincipal();
		SysUser sysUser=sysUserService.findByIdSysUser(account);
		SysRole sysRole=sysUserService.findByIdSysRole(sysUser.getUser_id());
		List<SysMenuExtend> list=null;
		if(sysRole!=null) {
			list=sysUserService.findByIdSysMenu(sysRole.getRole_id());
		}
		model.addAttribute("list", list);
		HttpSession session=req.getSession();
		session.setAttribute("user", sysUser);
		return "backstage/index";
	}
	
	/**
	 * @throws Exception 
	 * @Title: login   
	 * @Description: 采用shiro的内置登录  
	 * @param: @param req
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("userlogin")
	public String login(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		String shiroLoginFailure=(String) req.getAttribute("shiroLoginFailure");
		if(shiroLoginFailure!=null) {
			if(UnknownAccountException.class.getName().equals(shiroLoginFailure)) {
				getWirte(resp,"没有此用户");
			}else if(IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) {
				getWirte(resp,"密码错误");
			}else if(shiroLoginFailure.equals("verificationCodeError")) {
				getWirte(resp,"验证码错误");
			}else if(LockedAccountException.class.getName().equals(shiroLoginFailure)) {
				getWirte(resp, "账号被冻结");
			}
		}
		return "backstage/login";
	}
	
	/**
	 * @param resp 
	 * @param req 
	 * @Title: getWirte   
	 * @Description: ajax异步请求,发送json 
	 * @param: @param data
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static void getWirte(HttpServletResponse resp,Object data) {
		try {
			if(data!=null&&!data.equals("")) {
				PrintWriter	out = resp.getWriter();
				String json=JsonUtils.objectToJson(data);
				out.print(json);
				out.flush();
				out.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @Title: selectSysUser   
	 * @Description:显示所有管理员信息 
	 * @param: @param model
	 * @param: @param sysUserExtend
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("selectSysUser")
	public String selectSysUser(Model model,SysUserExtend sysUserExtend,
			@RequestParam(value="page",defaultValue="1")int page,HttpServletRequest req) throws Exception {
		if(sysUserExtend!=null)initSysUser(model,sysUserExtend);
		SysDept sysDept=getSysDept(req);
		sysUserExtend.setCascade_id(sysDept.getCascade_id());
		PageHelper.startPage(page, 5);
		List<SysUserExtend> list = sysUserService.selectSysUser(sysUserExtend);
		PageInfo<SysUserExtend> pageInfo=new PageInfo<SysUserExtend>(list);
		model.addAttribute("list", list);
		model.addAttribute("p", pageInfo);
		return "backstage/rwl/sysUser";
	}
	
	public SysDept getSysDept(HttpServletRequest req) throws Exception {
		SysUser sysuser= (SysUser) req.getSession().getAttribute("user");
		SysDept sysDept=sysDeptService.findByIdSysDept(sysuser.getDept_id());
		return sysDept;
	}
	
	/**
	 * 
	 * @Title: initSysUser   
	 * @Description: 用户模糊查询
	 * @param: @param model
	 * @param: @param sysUserExtend      
	 * @return: void      
	 * @throws
	 */
	private void initSysUser(Model model, SysUserExtend sysUserExtend) {
		String account=sysUserExtend.getAccount();
		String username=sysUserExtend.getUsername();
		int dept_id=sysUserExtend.getDept_id();
		if(account!=null) {
			model.addAttribute("account", account);
		}
		if(username!=null) {
			model.addAttribute("username", username);
		}
		if(String.valueOf(dept_id)!=null&&!String.valueOf(dept_id).equals("-1")) {
			model.addAttribute("dept_id", dept_id);
		}
	}
	
	/**
	 * @Title: selectSysDept   
	 * @Description:查询所有的组织机构，以json返回到客户端
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: List<SysDept>      
	 * @throws
	 */
	@RequestMapping("selectSysDept")
	public @ResponseBody List<SysDept> selectSysDept(HttpServletRequest req) throws Exception{
		HashMap<String, String> map=new HashMap<String,String>();
		SysDept sysDept=getSysDept(req);
		map.put("cascade_id",sysDept.getCascade_id() );
		List<SysDept> list = sysDeptService.selectSysDept(map);
		return list;
	}
	
	/**
	 * 
	 * @Title: insertSysUser   
	 * @Description: 新增用户管理员和修改用户
	 * @param: @param sysUserExtend
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("insertSysUser")
	public String insertSysUser(SysUserExtend sysUserExtend,HttpServletRequest req) throws Exception {
		//获取当前用户id
		HttpSession session=req.getSession();
		SysUser sysUser=(SysUser) session.getAttribute("user");
		int user_id=sysUser.getUser_id();
		String account=sysUser.getAccount();
		if(sysUserExtend.getUser_id()==0) {
			sysUserService.insertSysUser(sysUserExtend,user_id);
		}else {
			sysUserService.updateSysUser(sysUserExtend, user_id);
			SysUser s=sysUserService.findByIdSysUser(account);
			session.setAttribute("user", s);
		}
		return "redirect:selectSysUser";
	}
	
	/**
	 * 
	 * @Title: querySysUser   
	 * @Description: 通过id查询用户管理员,再把信息已流的方式json传送到模态框中  
	 * @param: @param user_id
	 * @param: @param resp
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("querySysUser")
	public String querySysUser(@RequestParam("user_id") Integer user_id,HttpServletResponse resp) throws Exception {
		SysUserExtend sysUserExtend=sysUserService.findByIdSelectSysUser(user_id);
		getWirte(resp, sysUserExtend);
		return "backstage/index";
	}
	
	/**
	 * @Title: deleteSysUser   
	 * @Description: 通过id删除用户管理员  
	 * @param: @param user_id
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("deleteSysUser")
	public String deleteSysUser(@RequestParam("user_id")Integer user_id) throws Exception {
		sysUserService.deleteSysUser(user_id);
		return "redirect:selectSysUser";
	}
	
	/**
	 * @Title: findByIdSysUser   
	 * @Description:通过id查找用户,用户名如果存在就返回false   
	 * @param: @param account
	 * @param: @param account2
	 * @param: @param resp
	 * @param: @return
	 * @param: @throws Exception      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("findByIdSysUser")
	public String findByIdSysUser(@RequestParam("account") String account,
			@RequestParam("account2") String account2,HttpServletResponse resp) throws Exception {
			Map<Object,Object> map=new HashMap<Object,Object>();
			SysUser sysUser=sysUserService.findByIdSysUser(account);
			if(sysUser==null) {
				map.put("valid", true);
			}else {
				if(account.equals(account2)) {
					map.put("valid", true);
				}else {
					map.put("valid", false);
				}
			}
			getWirte(resp, map);
			return "backstage/index";
	}
	
	/**
	 * @Title: unfreeze   
	 * @Description: 通过用户id解冻   
	 * @param: @param user_id
	 * @param: @throws Exception      
	 * @return: void      
	 * @throws
	 */
	@RequestMapping("unfreezeSysUser")
	public String unfreeze(@RequestParam("user_id")int user_id) throws Exception {
		HashMap<String,Object> map=new HashMap<String,Object>();
		map.put("user_id", user_id);
		map.put("status", "1");
		sysUserService.unfreezeSysUser(map);
		return "redirect:selectSysUser";
	}
}
